package com.example.wuyeguanli.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.example.wuyeguanli.R;
import com.example.wuyeguanli.entiy.Response;
import com.example.wuyeguanli.entiy.VisitInfo;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.DataValidator;
import com.example.wuyeguanli.tools.VisitorIdGenerator;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class VisitorManagementActivity extends AppCompatActivity {
    private final String TAG = "ApiClient";
    private Button btnBack, btnSubmit;
    private EditText editRoom, registerName, registerPhone, registerReason;
    private TextView timeText; // 改为TextView以显示选择的时间
    private ProgressBar loadingProgress;
    private final ApiClient apiClient = new ApiClient();
    private Calendar startCalendar = Calendar.getInstance();
    private Calendar endCalendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visitormanagement);
        if(getSupportActionBar() != null) getSupportActionBar().hide();

        initViews();
        setupInitialTime();
        timeText.setOnClickListener(v -> showStartDateTimePicker());
        btnBack.setOnClickListener(v -> finish());
        btnSubmit.setOnClickListener(v -> handleSubmit());
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnSubmit = findViewById(R.id.btn_submit);
        editRoom = findViewById(R.id.edit_room);
        registerName = findViewById(R.id.register_name);
        registerPhone = findViewById(R.id.register_phone);
        registerReason = findViewById(R.id.register_reason);
        timeText = findViewById(R.id.time_text); // 现在是TextView
        loadingProgress = findViewById(R.id.loading_progress);
    }

    private void setupInitialTime() {
        // 默认结束时间比开始时间晚2小时
        endCalendar.add(Calendar.HOUR_OF_DAY, 2);
        updateDateTimeDisplay();
    }

    // 步骤1: 显示开始日期的选择器
    private void showStartDateTimePicker() {
        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            startCalendar.set(year, month, dayOfMonth);
            // 日期选定后，显示开始时间的选择器
            showStartTimePicker();
        }, startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH), startCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    // 步骤2: 显示开始时间的选择器
    private void showStartTimePicker() {
        new TimePickerDialog(this, (timeView, hourOfDay, minute) -> {
            startCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            startCalendar.set(Calendar.MINUTE, minute);
            // 开始时间选定后，自动弹出结束日期的选择器
            showEndDateTimePicker();
        }, startCalendar.get(Calendar.HOUR_OF_DAY), startCalendar.get(Calendar.MINUTE), true).show();
    }

    // 步骤3: 显示结束日期的选择器
    private void showEndDateTimePicker() {
        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            endCalendar.set(year, month, dayOfMonth);
            // 结束日期选定后，显示结束时间的选择器
            showEndTimePicker();
        }, endCalendar.get(Calendar.YEAR), endCalendar.get(Calendar.MONTH), endCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    // 步骤4: 显示结束时间的选择器
    private void showEndTimePicker() {
        new TimePickerDialog(this, (timeView, hourOfDay, minute) -> {
            endCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            endCalendar.set(Calendar.MINUTE, minute);
            // 所有时间都选定后，更新显示
            updateDateTimeDisplay();
        }, endCalendar.get(Calendar.HOUR_OF_DAY), endCalendar.get(Calendar.MINUTE), true).show();
    }

    private void updateDateTimeDisplay() {
        // 使用能显示日期的格式
        SimpleDateFormat displayFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        String displayText = displayFormat.format(startCalendar.getTime()) + "\n至\n" + displayFormat.format(endCalendar.getTime());
        timeText.setText(displayText);
    }

    private void handleSubmit() {
        setLoadingState(true);
        if (!validateInputs()) {
            setLoadingState(false);
            return;
        }

        String visitorId = VisitorIdGenerator.generate();
        SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        String startTime = isoFormat.format(startCalendar.getTime());
        String endTime = isoFormat.format(endCalendar.getTime());

        VisitInfo visitInfo = new VisitInfo(
                visitorId,
                registerName.getText().toString(),
                registerPhone.getText().toString(),
                editRoom.getText().toString(),
                registerReason.getText().toString(),
                startTime,
                endTime,
                null
        );

        apiClient.addVisitInfo(visitInfo, new ApiClient.OnCompleteListener<Response<Object>>() {
            @Override
            public void onSuccess(Response<Object> data) {
                setLoadingState(false);
                if (data != null && "success".equals(data.getState())) {
                    Toast.makeText(VisitorManagementActivity.this, "访客信息登记成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(VisitorManagementActivity.this, data != null ? data.getError() : "登记失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void OnError(Throwable error) {
                setLoadingState(false);
                Log.e(TAG, "AddVisitInfo OnError: ", error);
                Toast.makeText(VisitorManagementActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean validateInputs() {
        if (!DataValidator.isValidRoomNumber(editRoom.getText().toString()) ||
                !DataValidator.isValidName(registerName.getText().toString()) ||
                !DataValidator.isValidPhoneNumber(registerPhone.getText().toString()) ||
                !DataValidator.isNotEmpty(registerReason.getText().toString())) {
            Toast.makeText(this, "请检查所有输入项是否正确填写", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (startCalendar.after(endCalendar)) {
            Toast.makeText(this, "结束时间不能早于开始时间", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void setLoadingState(boolean isLoading) {
        loadingProgress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        editRoom.setEnabled(!isLoading);
        registerName.setEnabled(!isLoading);
        registerPhone.setEnabled(!isLoading);
        registerReason.setEnabled(!isLoading);
        timeText.setEnabled(!isLoading);
        btnSubmit.setEnabled(!isLoading);
    }
}